<template>
    <div class="components_edit_modal">
        <el-dialog width="1200px" :title="dialogName" :visible.sync="state" :show-close="true" :close-on-click-modal="false" class="dialog_personal">
            <el-form>
               <div ref="professionParams">
                   <div class="el-form-item lineblock">
                       <label class="el-form-item__label">计划名称：</label>
                       <span class="el-form-item__content">{{dialogName}}</span>
                   </div>
                   <div class="el-form-item is-required lineblock">
                       <label class="el-form-item__label">教学大纲：</label>
                       <div class="el-form-item__content">
                           <pl-upload :initionData="attachment" :displaymode="'text'"  :imageOnly="false" :multiFile="false" @reloadFiles="reloadFiles" ></pl-upload>
                           <p style="font-size: 12px; color:#fa5555; line-height: 20px;">（注：此处只能上传一个文件，如有多个请压缩成一个后再上传）</p>
                       </div>
                   </div>

                <el-tabs v-model="tab" type="border-card">
                    <el-tab-pane label="手动录入" name="handEntry">
                        <div class="components_searchs">
                            <span class="tit">选择周次：</span>
                            <el-input  placeholder="请选择周次" v-model="weekShowLine" disabled></el-input>

                            <el-button type="primary" @click="showWeekSelector()"  size="mini">点击选择</el-button>
                        </div>
                        <div class="scrollBarX">
                            <el-table :data="weekSelecttList"  border stripe style="width: 100%" class="components_edit_tables" height="350">
                                <el-table-column  prop="teachWeek" :formatter="formatWeek"  label="周次" align="center" width="70"></el-table-column>
                                <!-- <el-table-column  prop="beginTime"  label="开始时间"  align="center" width="160">
                                    <template slot-scope="scope">
                                         <el-date-picker
                                            v-model="weekSelecttList[scope.row.index].beginTime"
                                            type="date"
                                            placeholder="选择日期">
                                          </el-date-picker>
                                    </template>
                                </el-table-column>
                                <el-table-column  prop="endTime"  label="结束时间" align="center" width="160">
                                    <template slot-scope="scope">
                                         <el-date-picker
                                            v-model="weekSelecttList[scope.row.index].endTime"
                                            type="date"
                                            placeholder="选择日期">
                                          </el-date-picker>
                                    </template>
                                </el-table-column> -->
                                <!-- <el-table-column  label="课程" align="center" width="160">
                                    <template slot-scope="scope">
                                        <el-select v-model="weekSelecttList[scope.row.index].courseNo" filterable placeholder="请选择课程" >
                                            <el-option v-for="course in courseList" :key="course.courseNo" :label="course.courseName" :value="course.courseNo" >
                                            </el-option>
                                        </el-select>
                                    </template>
                                </el-table-column> -->
                                <el-table-column  prop="classPeriod"  label="课时" width="120" align="center">
                                    <template slot-scope="scope">
                                        <el-input-number size="mini" width="60" v-model="scope.row.classPeriod" :min="2" :max="999">
                                        </el-input-number>
                                    </template>
                                </el-table-column>
                               <el-table-column   prop="resourceRequirement"  label="资源要求" align="center">
                                   <template slot-scope="scope">
                                        <el-input v-model="scope.row.resourceRequirement" placeholder="请输入资源要求" clearable></el-input>
                                    </template>
                               </el-table-column>
                               <el-table-column  prop="supportPoint"  label="支持点" align="center">
                                   <template slot-scope="scope">
                                        <el-input v-model="scope.row.supportPoint" placeholder="请输入支持点"  clearable></el-input>
                                    </template>
                               </el-table-column>
                               <el-table-column  prop="supportContent"  label="支持内容" align="center">
                                   <template slot-scope="scope">
                                        <el-input type="textarea" v-model="scope.row.supportContent" placeholder="请输入支持内容"   clearable></el-input>
                                    </template>
                               </el-table-column>
                               <el-table-column  prop="remark"  label="备注" align="center">
                                   <template slot-scope="scope">
                                        <el-input v-model="scope.row.remark" placeholder="请输入备注" clearable></el-input>
                                    </template>
                               </el-table-column>
                               <el-table-column label="操作" align="center" width="100">
                                    <template slot-scope="scope">
                                        <el-button type="text" size="small" @click="addItem(scope.row,scope.$index)">复制</el-button>
                                        <el-button type="text" size="small" @click="deleteItem(scope.$index)" >删除</el-button>
                                    </template>
                               </el-table-column>
                            </el-table>
                        </div>

                    </el-tab-pane>
                    <el-tab-pane label="导入" name="xlsxEntry" style="min-height: 150px;">
                        <!--  <el-upload
                               class="components_upload"
                               :action="upload.url"
                               :auto-upload="false"
                               accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                               :limit="1"
                               :on-change="handleUploadChange"
                               >
                               <el-button size="mini" type="primary">选择文件</el-button>
                               <div slot="tip" class="el-upload__tip">只能上传模版文件</div>
                           </el-upload>
                                                <el-button type="primary" style="margin-top:10px" size="mini" @click="downLoadExcel">下载导入模板</el-button> -->
                        <h2 style="color: #999;text-align: center; padding-top: 50px;">功能开发中，敬请期待……</h2>
                    </el-tab-pane>
                </el-tabs>
                </div>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" size="small" @click="updateTeachSupport">保 存 草 稿</el-button>
                <el-button type="primary" @click="submit" size="small">提 交</el-button>
                <el-button @click="state = false"  size="small">关 闭</el-button>
            </div>
        </el-dialog>
        <week-selector
            :datas="weekPassList"
             ref="weekSelector"/>
    </div>
</template>

<script>
    import {enums} from '@/constant'
    import PlUpload from "../../../common/PlUpload"
    import week_selector from "../../../common/week-selector"
    import {config} from "../../../../config.js";
    export default {
        components: {
            "pl-upload":PlUpload,
            "week-selector":week_selector
        },
        data() {
            return {
                state:false,
                dialogName:null,
                subject: null,
                weekShowLine:null,
                row:null,
                tab:"handEntry",
                attachment:[], //  文件列表
                weekList:[],//请求的数据
                weekSelecttList:[],//整理后的数据格式
                courseList:[],//课程列表
                weekPassList:[], //传递给周期控件的值
                uploadFile:null,//上传文件
                upload: {
                    url:api.teachSupport.importExcel,
                    fileList:[],
                },
            }
        },
        created() {

        },
        mounted() {},
        methods: {
            // 打开模态框
            showDialog(row){
                this.row=row;
                this.subject = row.schoolName + "-" +　row.secondSchoolName + "-" + row.professionName + "-" + row.semester + "期";
                this.state = true;
                this.getTeachSupportDetail(row.teachSupportBase.id);
                this.getPermissionCoursesByGrade();
                this.getWeekList();
            },
            //获取详情
            getTeachSupportDetail(id){
                let self = this;
                let weekShowLine = [];;
                self.axios.get(api.teachSupport.detail+id)
                .then((response) => {
                    if(response.data.success){
                        // console.log(JSON.stringify(response.data.data));
                        self.dialogName = response.data.data.planName;
                        let supportPlanList = response.data.data.teachSupportPlanList;
                        let weekSelecttList = [];
                        for(let i=0;i<supportPlanList.length;i++){
                            weekShowLine.push(supportPlanList[i].teachWeek);
                            let item = {
                                index:i,
                                id:supportPlanList[i].id,
                                teachWeek:supportPlanList[i].teachWeek,
                                beginTime:supportPlanList[i].beginTime,
                                endTime:supportPlanList[i].endTime,
                                courseNo:supportPlanList[i].courseNo,
                                classPeriod:supportPlanList[i].classPeriod,
                                resourceRequirement:supportPlanList[i].resourceRequirement,
                                supportPoint:supportPlanList[i].supportPoint,
                                supportContent:supportPlanList[i].supportContent,
                                remark:supportPlanList[i].remark,
                            }
                            weekSelecttList.push(item);
                        }
                        self.weekSelecttList = weekSelecttList;
                        if(response.data.data.attachment){
                            self.attachment = response.data.data.attachment;
                        }
                        self.weekShowLine = weekShowLine.join(",");
                    }else {
                        self.$message.error(response.data.msg);
                    }
                });
            },
            handleUploadChange(file, fileList){
                // 校验文件名 过滤文件
                if(file.name.indexOf(".xlsx") == -1){
                    this.$message.error("只能上传教学服务支持计划模版Excel文件");
                    fileList.splice(0,fileList.length);
                    return;
                }
                // 设置数据
                this.uploadFile = file.raw;
                fileList.splice(0,fileList.length);
                fileList.push(file);
            },
            reloadFiles: function (files) {
                // console.log("----------->"+JSON.stringify(files)+"<----------------");
                let vm = this;
                this.attachment = [];
                files.forEach((item,idnex)=>{
                    let model = {
                        fileRealName: item.fileRealName,
                        objectKey: item.objectKey
                    }

                    this.attachment.push(model)
                })
            },

            getPermissionCoursesByGrade(){
                let self = this;
                self.axios.get(api.queryTrainPlanCourseByUserId,{
                    params: {
                        grade: self.row.grade
                    }
                }).then((response) => {
                    // console.log(JSON.stringify(response.data.data));
                    self.courseList = JSON.parse(JSON.stringify(response.data.data));
                });
            },
            getWeekList(){
                let self = this;
                self.axios.get(api.schoolCalendar.getWeek+self.row.professionId,{
                    params: {
                        grade: self.row.grade,
                        semester:self.row.semester
                    }
                }).then((response) => {
                    // console.log(JSON.stringify(response.data.data));
                    self.weekList = JSON.parse(JSON.stringify(response.data.data));
                });
            },
            //整理数据，打开 选择周弹窗
            showWeekSelector(){
                let weekList = this.weekList;
                let weekSelecttList = this.weekSelecttList;
                let lineCount =weekList.length/7;

                if(weekList.length % 7 >0){
                    lineCount += 1;
                }
                let weekCurrentList=[];

                for(let i=0;i<lineCount;i++){
                    let weekItem=[];
                    for(let j=1;j<=7;j++){
                        if(7*i+j<=weekList.length){
                            let bool_temp = false;
                            //判断传过去的值回显问题
                            for(let num=0;num<weekSelecttList.length;num++){
                                if(weekSelecttList[num].teachWeek == weekList[7*i+j-1].week){
                                    bool_temp = true;
                                }
                            }

                            weekItem.push({
                                id:weekList[7*i+j-1].id,
                                teachWeek:weekList[7*i+j-1].week,
                                beginTime:weekList[7*i+j-1].startDate,
                                endTime:weekList[7*i+j-1].endDate,
                                select:bool_temp
                            });
                        }
                    }
                    weekCurrentList.push(weekItem);
                }
                this.weekPassList = weekCurrentList;
                this.$refs.weekSelector.showDialog();
            },

            putSelectWeekList(params){
                let weekShowLine =[];
                let weekCurrentList = params.data;
                let callBackWeekSelecttList=[];
                let weekSelecttList = this.weekSelecttList;


                for(let i=0;i<weekCurrentList.length;i++){
                    let item={};
                    //  查找某一教学周
                    let weekArr = _.filter(weekSelecttList, function(o) { return o.teachWeek == weekCurrentList[i].teachWeek; });

                    if(weekArr.length == 0){

                        item.index = i;
                        item.teachWeek = weekCurrentList[i].teachWeek;
                        item.beginTime = weekCurrentList[i].beginTime;
                        item.endTime = weekCurrentList[i].endTime;
                        weekArr.push(item);
                    }
                    callBackWeekSelecttList = _.concat(callBackWeekSelecttList,weekArr);
                    weekShowLine.push(weekCurrentList[i].teachWeek);
                }

                this.weekSelecttList=callBackWeekSelecttList;
                this.weekShowLine = weekShowLine.join(",");

            },
            updateTeachSupport(){

                let self = this;
                if(self.tab != "handEntry"){
                    this.importBtn();
                    return;
                }
                let weekSelecttList = self.weekSelecttList;
                 if(_.isEmpty(weekSelecttList)){
                    self.$message({
                        type: 'warn',
                        message: '请至少填入一条教学服务支持计划',
                    });
                    return;
                }
                let planList=[];
                for(let i=0;i<weekSelecttList.length;i++){
                    weekSelecttList[i].courseNo = self.row.courseNo;
                    weekSelecttList[i].courseName = self.row.courseName;
                    if(weekSelecttList[i].courseNo == null){
                            self.$message({
                            type: 'warn',
                            message: '第'+ weekSelecttList[i].teachWeek +'周计划请选择课程',
                        });
                        return;
                    }
                    let item={
                        id:weekSelecttList[i].id,
                        baseId:this.row.teachSupportBase.id,
                        beginTime:weekSelecttList[i].beginTime,
                        endTime:weekSelecttList[i].endTime,
                        classPeriod:weekSelecttList[i].classPeriod,
                        courseName:weekSelecttList[i].courseName,
                        courseNo:weekSelecttList[i].courseNo,
                        remark:weekSelecttList[i].remark,
                        resourceRequirement:weekSelecttList[i].resourceRequirement,
                        supportContent:weekSelecttList[i].supportContent,
                        supportPoint:weekSelecttList[i].supportPoint,
                        teachWeek:weekSelecttList[i].teachWeek,
                        attachment:self.attachment
                    }
                    planList.push(item);
                }
                // console.log(JSON.stringify(planList)) ;
                self.axios.put(api.teachSupport.update,planList
                ).then((response) => {
                    if (response.data.success) {
                        self.$message({
                            type: 'success',
                            message: response.data.msg,
                        });
                        self.$parent.$refs.teachSupportTable.$emit('vuetable:refresh')
                        self.state = false;
                     } else {
                        self.$message.error(response.data.msg);
                    }

                });
            },
            // 提交
            submit(){
                let self = this;
                if(self.tab != "handEntry"){
                    this.importBtn();
                    return;
                }
                let weekSelecttList = self.weekSelecttList;

                 if(_.isEmpty(weekSelecttList)){
                    self.$message({
                        type: 'warn',
                        message: '请至少填入一条教学服务支持计划',
                    });
                    return;
                }
                let planList=[];
                for(let i=0;i<weekSelecttList.length;i++){
                    weekSelecttList[i].courseNo = self.row.courseNo;
                    weekSelecttList[i].courseName = self.row.courseName;
                    if(weekSelecttList[i].courseNo == null){
                            self.$message({
                            type: 'warn',
                            message: '第'+ weekSelecttList[i].teachWeek +'周计划请选择课程',
                        });
                        return;
                    }
                    let item={
                        id:weekSelecttList[i].id,
                        baseId:this.row.teachSupportBase.id,
                        beginTime:weekSelecttList[i].beginTime,
                        endTime:weekSelecttList[i].endTime,
                        classPeriod:weekSelecttList[i].classPeriod,
                        courseName:weekSelecttList[i].courseName,
                        courseNo:weekSelecttList[i].courseNo,
                        remark:weekSelecttList[i].remark,
                        resourceRequirement:weekSelecttList[i].resourceRequirement,
                        supportContent:weekSelecttList[i].supportContent,
                        supportPoint:weekSelecttList[i].supportPoint,
                        teachWeek:weekSelecttList[i].teachWeek,
                        attachment:self.attachment
                    }
                    planList.push(item);
                }
               //  打开流程定义界面
                    let data = {
                        actionType: "update",
                        flowSubject: self.subject,
                        businessCode: `jx_teach_support_base`,
                        businessId: self.row.teachSupportBase.id,
                        businessForm: planList,
                        businessUrl: api.teachSupport.update
                    };
                    self.$store.commit(`FLOW_INIT`, {"dialogState": true, "data": data});
            },
            importBtn(){
              let self = this;
              let formData = new FormData();
              formData.append("uploadFile",this.uploadFile);
              formData.append("baseId",this.row.teachSupportBase.id);
              let config = {
                headers: {
                  'Content-Type': 'multipart/form-data'  //之前说的以表单传数据的格式来传递fromdata
                }
              };
              this.axios.post(api.teachSupport.importExcel,formData,config).then(function (response) {
                  // console.log(response);
                  if(response.data.success){
                    self.$message.success(response.data.msg);
                  }else{
                    self.$message.error(response.data.msg);
                  }
                self.$parent.$refs.teachSupportTable.$emit('vuetable:refresh')
              });
              this.dialogFormVisible = false;
            },
            getCourseNameByCourseNo(courseNo){
                let courseList = this.courseList;
                for(let i=0;i<courseList.length;i++){
                    if(courseList[i].courseNo == courseNo){
                        return courseList[i].courseName;
                    }
                }
            },
            formatWeek(row, column, cellValue){
                return "第"+cellValue+"周";
            },
            downLoadExcel(){
                let self = this;
              let href = config.BASE_URL+api.teachSupport.downExcel;
              href += "?Authorization="+localStorage.getItem("userToken");
              window.location.href = href;
            },
            // 添加一项
            addItem(val,index){
                let item = {};
                item.beginTime = val.beginTime;
                item.classPeriod = val.classPeriod;
                item.resourceRequirement = val.resourceRequirement;
                item.supportPoint = val.supportPoint;
                item.supportContent = val.supportContent;
                item.remark = val.remark;
                item.endTime = val.endTime;
                item.teachWeek = val.teachWeek;
                this.weekSelecttList.splice(index+1,0,item);
            },
            //删除某一项
            deleteItem(index){
                this.weekSelecttList.splice(index,1);
            }
        },


    };
</script>
<style scoped>
.el-input-number--mini{
    width: 90px;
}
.components_edit_modal .el-form-item{
    margin-bottom: 0;
}
.components_edit_modal .el-form-item__label{
    width: 90px;
}
.el-form-item{
    margin-bottom: 0;
}
.selectContainer{
    background-color: #fff;
    margin-left: 25px;
    width:210px;
    height:181px;
    border: 1px solid #00BBBD;
}
.selectContainer .item{
    width:30px;
    height:30px;
    text-align: center;
}
.opration_button{
    margin:10px;
}
</style>